import React from 'react';
import { useResizeObserver, useDebounceFn, useUnmount } from '@/hooks';

function Resizer(props) {
    const { children, onResize = () => {}, ...restProps } = props;

    const divRef = React.useRef(null);

    const { run, cancel } = useDebounceFn(
        (entry) => {
            const { bottom, height, left, right, top, width, x, y } = entry.contentRect;

            onResize({
                bottom,
                height,
                left,
                right,
                top,
                width,
                x,
                y,
                scrollWidth: divRef.current.scrollWidth,
                scrollHeight: divRef.current.scrollHeight,
            });
        },
        { wait: 200 }
    );

    useResizeObserver(divRef, run);

    useUnmount(cancel);

    return (
        <div ref={divRef} {...restProps}>
            {children}
        </div>
    );
}

export default Resizer;
